package com.whosly.demo.benchmark.sortalgorithms.bucket;

import com.whosly.demo.benchmark.sortalgorithms.ISortingAlgorithms;

import java.util.ArrayList;
import java.util.List;

/**
 * 桶排序（Bucket Sort）
 *
 * @author fengyang
 * @date 2023/6/13 上午11:43
 * @see <a href="fengyang@stoneatom.com">mailTo: fengyang@stoneatom.com</a>
 */
public class BucketSort implements ISortingAlgorithms
{
    /**
     * 该数值的选择对性能至关重要，性能最好时每个桶都均匀放置所有数值，反之最差
     */
    private int bucketSize;

    public BucketSort(int bucketSize)
    {
        this.bucketSize = bucketSize;
    }

    @Override
    public int[] sorting(int[] arr)
    {
        return new int[0];
    }

    private List<Integer> bucketSort(List<Integer> arr, int bucketSize) {
        int len = arr.size();
        if (len < 2 || this.bucketSize == 0) {
            return arr;
        }

        int minVal = arr.get(0), maxVal = arr.get(0);
        for (int i = 1; i < len; i++) {
            if (arr.get(i) < minVal) {
                minVal = arr.get(i);
            } else if (arr.get(i) > maxVal) {
                maxVal = arr.get(i);
            }
        }
        int bucketNum = (maxVal - minVal) / this.bucketSize + 1;

        List<List<Integer>> bucket = new ArrayList<>();
        for (int i = 0; i < bucketNum; i++) {
            bucket.add(new ArrayList<>());
        }
        for (int val : arr) {
            int idx = (val - minVal) / this.bucketSize;
            bucket.get(idx).add(val);
        }
        for (int i = 0; i < bucketNum; i++) {
            if (bucket.get(i).size() > 1) {
                bucket.set(i, bucketSort(bucket.get(i), this.bucketSize / 2));
            }
        }

        List<Integer> result = new ArrayList<>();
        for (List<Integer> val : bucket) {
            result.addAll(val);
        }
        return result;
    }

}
